package com.ibm.risk.irmp.base.seq.service;


import com.ibm.risk.irmp.base.se.service.SeqService;
import com.ibm.risk.irmp.base.seq.dao.SeqRepository;
import com.ibm.risk.irmp.base.seq.entity.SeqEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Primary
@Slf4j
public class SeqServiceImpl implements SeqService {
    @Autowired
    SeqRepository seqRepository;

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public int getNextSeq(String seqName, String group) {
        String realName = seqName;
        if (!StringUtils.isEmpty(group) ) {
            realName = realName + "-" + group;
        }
        SeqEntity entity = seqRepository.findById(realName).orElse(null);
        if (entity == null) {
            entity = new SeqEntity();
            entity.setSeqName(realName);
        }
        entity.setCurrentVal(entity.getCurrentVal() + 1);

        seqRepository.save(entity);
        return entity.getCurrentVal();
    }
}
